﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Net;
using System.Collections;
using System.Xml;
using System.Linq;
//using System.Xml.Linq;

using CommonUtils;
using TDAL = EzDAL.Auto2;
using TDALUtils = EzDAL.Utils;
using TConst = TERP.Constants;
using TUtils = TERP.Utils;
using TError = TERP.Errors;


namespace TERP.BizITS
{
    public partial class BizWater
	{
		#region // Private Utils:
		#endregion

        #region //Validate

		#region //CheckExistReceiptID
		#region //CheckExistReceiptID
		private void CheckExistReceiptID(
           ref ArrayList alParamsCoupleError
           , string strReceiptID
           , out DataTable dtStockOut
        )
        {
			dtStockOut = TDALUtils.DBUtils.GetTableContents(
                _dbCarSv // db
                , "Water_Receipt" // strTableName
                , "top 1 *" // strColumnList
                , "" // strClauseOrderBy
				, "ReceiptID", "=", strReceiptID // arrobjParamsTriple item
             );

			if (dtStockOut == null || dtStockOut.Rows.Count == 0)
            {

                throw CMyException.Raise(
                    TError.ErrITS.Its_ReceiptID_Not_Found
                    , null
                    , alParamsCoupleError.ToArray()
                    );
            }
        }
        #endregion
        #endregion


        #endregion

        #region //WaterReceipt

		#region Its_Receipt_Get
		public DataSet Its_Receipt_Get(
        string strGWUserCode
        , string strGWPassword
        , string strTid
        , string strPartnerCode
        , string strPartnerUserCode
        , string strLanguageCode
        , string strReceiptDConditionList
        , string strDateReceiptConditionList
		, string strCusIDConditionList
        )
        {

            #region // Temp:

            DataSet mdsFinal = CMyDataSet.NewMyDataSet(strTid);

            int nTidSeq = 0;
            bool bNeedTransaction = false;
			string strFunctionName = "Its_StockOut_Get";
			string strErrorCodeDefault = TError.ErrITS.Its_StockOut_Get;
            ArrayList alParamsCoupleError = new ArrayList(new object[]{

					"strFunctionName", strFunctionName
                    , "strReceiptDConditionList", strReceiptDConditionList
					, "strDateReceiptConditionList", strDateReceiptConditionList
                    ,"strCusIDConditionList",strCusIDConditionList
					});

            #endregion

            try
            {

                #region // Init:

                _dbCarSv.AppUserID = strPartnerUserCode;

                if (bNeedTransaction) _dbCarSv.BeginTransaction();

                // Write request log:

                _log.WriteLogAsync(

                _strConfig_GwUserCode // strGwUserCodeForLog

                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog

                , strTid // strAppTid

                , strPartnerCode // strAppServiceCode

                , strPartnerUserCode // strAppUPartCode

                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime

                , TError.Error.NoError // strAppErrorCode

                , strFunctionName // strAppLogType1

                , "REQUEST" // strAppLogType2

                , "" // strAppLogType3

                , strLanguageCode // strAppLanguageCode

                , "" // strAppRemark

                , TUtils.CUtils.ParamsCouple2ParamsTriple(alParamsCoupleError, 1, "").ToArray() // arrobjParamsTriple

                );

                // Check Valid Tid:

                myUtils_ValidateId(

                ref alParamsCoupleError // alParamsCoupleError

                , strTid // strTid

                , TError.ErrITS.CommonInvalidTid // strErrCodeWhenInvalid

                );

                #endregion

                #region // Build Sql:

                ArrayList alParamsCoupleSql = new ArrayList();

                string strSqlGetData = @"
						SELECT
                               t.*
                        FROM Water_Receipt t with (nolock)
						WHERE (1=1)
                                    zzzzClauseWhereReceiptIDConditionList
                                    zzzzClauseWhereDateReceiptConditionList
									zzzzClauseWhereCusIDConditionList
									;
				";

				string zzzzClauseWhereReceiptIDConditionList = SqlUtils.BuildClause("and", "t.ReceiptID", strReceiptDConditionList, "@p", ref alParamsCoupleSql);
				string zzzzClauseWhereDateReceiptConditionList = SqlUtils.BuildClause("and", "t.DateReceipt", strDateReceiptConditionList, "@p", ref alParamsCoupleSql);
				string zzzzClauseWhereCusIDConditionList = SqlUtils.BuildClause("and", "t.CusID", strCusIDConditionList, "@p", ref alParamsCoupleSql);
				
				

                strSqlGetData = StringUtils.Replace(
                strSqlGetData
				, "zzzzClauseWhereReceiptIDConditionList", zzzzClauseWhereReceiptIDConditionList
				, "zzzzClauseWhereDateReceiptConditionList", zzzzClauseWhereDateReceiptConditionList
				, "zzzzClauseWhereCusIDConditionList", zzzzClauseWhereCusIDConditionList

                );

                #endregion

                #region // Get Data:
                myDebug_SaveSql(
                    _bDebugMode // bDebugMode
                    , ref alParamsCoupleError // alParamsCoupleError
                    , string.Format("strSql_{0}", strFunctionName) // strParamName
                    , strSqlGetData // strSql
                    );


                DataSet dsGetData = _dbCarSv.ExecQuery(

                strSqlGetData

                , alParamsCoupleSql.ToArray()

                );

                dsGetData.Tables[0].TableName = "Water_Receipt";
            
                DataUtils.MoveDataTable(ref mdsFinal, ref dsGetData);

                #endregion

                // Return Good:

                TDALUtils.DBUtils.CommitSafety(_dbCarSv);

                mdsFinal.AcceptChanges();

                return mdsFinal;

            }

            catch (Exception exc)
            {

                #region // Catch of try:

                // Rollback:

                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);

                // Return Bad:

                return TUtils.CProcessException.Process(

                ref mdsFinal

                , exc

                , strErrorCodeDefault
                , alParamsCoupleError.ToArray()

                );

                #endregion

            }

            finally
            {

                #region // Finally of try:

                // Rollback and Release resources:

                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);

                TDALUtils.DBUtils.ReleaseAllSemaphore(_dbCarSv_Sys, true);

                TUtils.CProcessException.Process(

                ref mdsFinal // mdsFinal

                , _log // log

                , _strConfig_GwUserCode // strGwUserCodeForLog

                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog

                , strFunctionName // strFunctionName

                , TUtils.CUtils.TidNext(strTid, ref nTidSeq) // strAppTid

                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime

                , strPartnerCode // strAppServiceCode

                , strPartnerUserCode // strAppUserCode

                , strLanguageCode // strLanguageCode

                , "" // strRemark"

                );

                #endregion

            }

        }

        #endregion

		#region //Its_Receipt_Create
		public DataSet Its_Receipt_Create(
			 string strGWUserCode
			 , string strGWPassword
			 , string strTid
			 , string strPartnerCode
			 , string strPartnerUserCode
			 , string strLanguageCode
			 , string strReceiptCode
			 , string strDateReceipt
			 , string strNote
			 , string strCusID
			 , string strAmount
			 , string strReceiptType
     )
        {
            #region // Temp:
            DataSet mdsFinal = CMyDataSet.NewMyDataSet(strTid);
            int nTidSeq = 0;
            bool bNeedTransaction = true;
			string strFunctionName = "Its_Receipt_Create";
            string strErrorCodeDefault = TError.ErrITS.Its_Receipt_Create;
            ArrayList alParamsCoupleError = new ArrayList(new object[]{
			"strFunctionName", strFunctionName
			, "strReceiptCode", strReceiptCode
			, "strDateReceipt", strDateReceipt
			, "strNote", strNote
			, "strCusID", strCusID
			, "strAmount",strAmount
			, "strReceiptType",strReceiptType
			});
            #endregion
            try
            {
                #region // Init:
                _dbCarSv.AppUserID = strPartnerUserCode;
                if (bNeedTransaction) _dbCarSv.BeginTransaction();
                // Write request log:
                _log.WriteLogAsync(
                _strConfig_GwUserCode // strGwUserCodeForLog
                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                , strTid // strAppTid
                , strPartnerCode // strAppServiceCode
                , strPartnerUserCode // strAppUPartCode
                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                , TError.Error.NoError // strAppErrorCode
                , strFunctionName // strAppLogType1
                , "REQUEST" // strAppLogType2
                , "" // strAppLogType3
                , strLanguageCode // strAppLanguageCode
                , "" // strAppRemark
                , TUtils.CUtils.ParamsCouple2ParamsTriple(alParamsCoupleError, 1, "").ToArray() // arrobjParamsTriple
                );
                // Check Valid Tid:
                myUtils_ValidateId(
                ref alParamsCoupleError // alParamsCoupleError
                , strTid // strTid
                , TError.ErrITS.CommonInvalidTid // strErrCodeWhenInvalid
                );
                #endregion

                #region // Check:

                #endregion

                #region // dt_Book:
                DataTable dt_Book = TDALUtils.DBUtils.GetSchema(_dbCarSv, "Water_Receipt").Tables[0];
                dt_Book.Rows.Add(dt_Book.NewRow());
                dt_Book.Rows[0]["ReceiptCode"] = strReceiptCode;
				if (!StringUtils.IsEmpty(strDateReceipt))
                {
					dt_Book.Rows[0]["DateReceipt"] = strDateReceipt;
                }

				if (!StringUtils.IsEmpty(strNote))
                {
					dt_Book.Rows[0]["Note"] = strNote;
                }

                
				if (!StringUtils.IsEmpty(strCusID))
				{
					dt_Book.Rows[0]["CusID"] = strCusID;
				}

				if (!StringUtils.IsEmpty(strAmount))
                {
					dt_Book.Rows[0]["Amount"] = strAmount;
                }
				if (!StringUtils.IsEmpty(strReceiptType))
				{
					dt_Book.Rows[0]["ReceiptType"] = strReceiptType;
				}

                //Save
				_dbCarSv.SaveData("Water_Receipt", dt_Book);

                //Get ID
                string strSqlGetTourID = @"select @@Identity ReceiptID;";
                Int32 iID = Convert.ToInt32(_dbCarSv.ExecQuery(strSqlGetTourID).Tables[0].Rows[0][0]);
				dt_Book.Rows[0]["ReceiptID"] = iID;
                #endregion

				#region //Process update debit
				ProcessUpdateCustomerDebit(strCusID, strAmount, strReceiptType);
				#endregion

                #region // Return data

				DataSet dsGetData = new DataSet();
                dsGetData.Tables.Add(dt_Book.Copy());
				dsGetData.Tables[0].TableName = "Water_Receipt";

                DataUtils.MoveDataTable(ref mdsFinal, ref dsGetData);

                #endregion

                // Return Good:
                TDALUtils.DBUtils.CommitSafety(_dbCarSv);
                mdsFinal.AcceptChanges();
                return mdsFinal;
            }
            catch (Exception exc)
            {
                #region // Catch of try:
                // Rollback:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);
                // Return Bad:
                return TUtils.CProcessException.Process(
                ref mdsFinal
                , exc
                , strErrorCodeDefault
                , alParamsCoupleError.ToArray()
                );
                #endregion
            }
            finally
            {
                #region // Finally of try:
                // Rollback and Release resources:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);
                TDALUtils.DBUtils.ReleaseAllSemaphore(_dbCarSv_Sys, true);
                TUtils.CProcessException.Process(
                ref mdsFinal // mdsFinal
                , _log // log
                , _strConfig_GwUserCode // strGwUserCodeForLog
                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                , strFunctionName // strFunctionName
                , TUtils.CUtils.TidNext(strTid, ref nTidSeq) // strAppTid
                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                , strPartnerCode // strAppServiceCode
                , strPartnerUserCode // strAppUserCode
                , strLanguageCode // strLanguageCode
                , " // strRemark"
                );
                #endregion
            }
        }

        #endregion

		#region //Its_Receipt_Update
		public DataSet Its_Receipt_Update(
			 string strGWUserCode
			 , string strGWPassword
			 , string strTid
			 , string strPartnerCode
			 , string strPartnerUserCode
			 , string strLanguageCode
			 , string strReceiptID
			 , string strReceiptCode
			 , string strDateReceipt
			 , string strNote
			 , string strCusID
			 , string strAmount
			 , string strReceiptType
     )
        {
            #region // Temp:
            DataSet mdsFinal = CMyDataSet.NewMyDataSet(strTid);
            int nTidSeq = 0;
            bool bNeedTransaction = true;
			string strFunctionName = "Its_Receipt_Update";
			string strErrorCodeDefault = TError.ErrITS.Its_Receipt_Update;
            ArrayList alParamsCoupleError = new ArrayList(new object[]{
			"strFunctionName", strFunctionName
			,"strReceiptID",strReceiptID
			, "strReceiptCode", strReceiptCode
			, "strDateReceipt", strDateReceipt
			, "strNote", strNote
			, "strCusID", strCusID
			, "strAmount",strAmount
			, "strReceiptType",strReceiptType
			});
            #endregion
            try
            {
                #region // Init:
                _dbCarSv.AppUserID = strPartnerUserCode;
                if (bNeedTransaction) _dbCarSv.BeginTransaction();
                // Write request log:
                _log.WriteLogAsync(
                _strConfig_GwUserCode // strGwUserCodeForLog
                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                , strTid // strAppTid
                , strPartnerCode // strAppServiceCode
                , strPartnerUserCode // strAppUPartCode
                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                , TError.Error.NoError // strAppErrorCode
                , strFunctionName // strAppLogType1
                , "REQUEST" // strAppLogType2
                , "" // strAppLogType3
                , strLanguageCode // strAppLanguageCode
                , "" // strAppRemark
                , TUtils.CUtils.ParamsCouple2ParamsTriple(alParamsCoupleError, 1, "").ToArray() // arrobjParamsTriple
                );
                // Check Valid Tid:
                myUtils_ValidateId(
                ref alParamsCoupleError // alParamsCoupleError
                , strTid // strTid
                , TError.ErrITS.CommonInvalidTid // strErrCodeWhenInvalid
                );
                #endregion

                #region // Check:
                DataTable dt_Book = null;
                this.CheckExistReceiptID(
                    ref alParamsCoupleError
                    , strCusID
                    , out dt_Book
                    );
                #endregion

                #region // dt_Book:
                ArrayList alColumnEffective = new ArrayList();
                alColumnEffective.Clear();


				dt_Book.Rows[0]["ReceiptCode"] = strReceiptCode; alColumnEffective.Add("ReceiptCode");
				if (!StringUtils.IsEmpty(strDateReceipt))
				{
					dt_Book.Rows[0]["DateReceipt"] = strDateReceipt; alColumnEffective.Add("DateReceipt");
				}

				if (!StringUtils.IsEmpty(strNote))
				{
					dt_Book.Rows[0]["Note"] = strNote; alColumnEffective.Add("Note");
				}


				if (!StringUtils.IsEmpty(strCusID))
				{
					dt_Book.Rows[0]["CusID"] = strCusID; alColumnEffective.Add("CusID");
				}

				if (!StringUtils.IsEmpty(strAmount))
				{
					dt_Book.Rows[0]["Amount"] = strAmount; alColumnEffective.Add("Amount");
				}
				if (!StringUtils.IsEmpty(strReceiptType))
				{
					dt_Book.Rows[0]["ReceiptType"] = strReceiptType; alColumnEffective.Add("ReceiptType");
				}

                //Save
                _dbCarSv.SaveData("Water_Receipt", dt_Book, alColumnEffective.ToArray());

                //Get ID
                Int32 iID = Convert.ToInt32(strCusID);
                #endregion

				#region //Process update debit
				ProcessUpdateCustomerDebit(strCusID, strAmount, strReceiptType);
				#endregion

				#region // Return data


				//Return data
				DataSet dsGetData = new DataSet();
                dsGetData.Tables.Add(dt_Book.Copy());
				dsGetData.Tables[0].TableName = "Water_Receipt";

                DataUtils.MoveDataTable(ref mdsFinal, ref dsGetData);

                #endregion

                // Return Good:
                TDALUtils.DBUtils.CommitSafety(_dbCarSv);
                mdsFinal.AcceptChanges();
                return mdsFinal;
            }
            catch (Exception exc)
            {
                #region // Catch of try:
                // Rollback:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);
                // Return Bad:
                return TUtils.CProcessException.Process(
                ref mdsFinal
                , exc
                , strErrorCodeDefault
                , alParamsCoupleError.ToArray()
                );
                #endregion
            }
            finally
            {
                #region // Finally of try:
                // Rollback and Release resources:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);
                TDALUtils.DBUtils.ReleaseAllSemaphore(_dbCarSv_Sys, true);
                TUtils.CProcessException.Process(
                ref mdsFinal // mdsFinal
                , _log // log
                , _strConfig_GwUserCode // strGwUserCodeForLog
                , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                , strFunctionName // strFunctionName
                , TUtils.CUtils.TidNext(strTid, ref nTidSeq) // strAppTid
                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                , strPartnerCode // strAppServiceCode
                , strPartnerUserCode // strAppUserCode
                , strLanguageCode // strLanguageCode
                , " // strRemark"
                );
                #endregion
            }
        }

        #endregion

		#region // Its_Receipt_Delete
		public DataSet Its_Receipt_Delete(
            string strGwUserCode
            , string strGwPassword
            , string strTid
            , string strPartnerCode
            , string strPartnerUserCode
            , string strLanguageCode
			, string strReceiptID
        )
        {
            #region // temp
            DataSet mdsFinal = CMyDataSet.NewMyDataSet(strTid);
            int nTidSeq = 0;
            bool bNeedTransaction = true;
			string strFunctionName = "Its_Receipt_Delete";
			string strErrorCodeDefault = TError.ErrITS.Its_Receipt_Delete;
            ArrayList alParamsCoupleError = new ArrayList(new object[]{
					"strFunctionName", strFunctionName
                   ,"strReceiptD",strReceiptID 
					});
            #endregion

            try
            {
                #region // Init:
                _dbCarSv.AppUserID = strPartnerUserCode;
                if (bNeedTransaction) _dbCarSv.BeginTransaction();

                // Write request log:
                _log.WriteLogAsync(
                    _strConfig_GwUserCode // strGwUserCodeForLog
                    , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                    , strTid // strAppTid
                    , strPartnerCode // strAppServiceCode
                    , strPartnerUserCode // strAppUserCode
                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                    , TError.Error.NoError // strAppErrorCode
                    , strFunctionName // strAppLogType1
                    , "REQUEST" // strAppLogType2
                    , "" // strAppLogType3
                    , strLanguageCode // strAppLanguageCode
                    , "" // strAppRemark
                    , TUtils.CUtils.ParamsCouple2ParamsTriple(alParamsCoupleError, 1, "").ToArray() // arrobjParamsTriple
                    );

                // Check Valid Tid:
                myUtils_ValidateId(
                    ref alParamsCoupleError // alParamsCoupleError
                    , strTid // strTid
                    , TError.ErrHTC.CommonInvalidTid // strErrCodeWhenInvalid
                    );
                #endregion

                #region //Receipt
                #region //Check
                DataTable dt_Book = null;
				this.CheckExistReceiptID
				(
                     ref alParamsCoupleError
					, strReceiptID
                    , out dt_Book
                 );

                #endregion

                #region // Save data
                string strSqlDelete = @"
						delete 
						from Water_Receipt
						where
							ReceiptID = @ReceiptID
						;
					";

                // Save:
                myDebug_SaveSql(
                    _bDebugMode // bDebugMode
                    , ref alParamsCoupleError // alParamsCoupleError
                    , string.Format("strSql_{0}", strFunctionName) // strParamName
                    , strSqlDelete // strSql
                    );
                _dbCarSv.ExecQuery(
                    strSqlDelete
					, "@ReceiptID", strReceiptID
                    );



                #endregion
                #endregion

                // Return Good:
                TDALUtils.DBUtils.CommitSafety(_dbCarSv);
                mdsFinal.AcceptChanges();
                return mdsFinal;
            }
            catch (Exception exc)
            {
                #region // Catch of try:
                // Rollback:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);

                // Return Bad:
                return TUtils.CProcessException.Process(
                    ref mdsFinal
                    , exc
                    , strErrorCodeDefault
                    , alParamsCoupleError.ToArray()
                    );
                #endregion
            }
            finally
            {
                #region // Finally of try:
                // Rollback and Release resources:
                TDALUtils.DBUtils.RollbackSafety(_dbCarSv);
                TDALUtils.DBUtils.ReleaseAllSemaphore(_dbCarSv_Sys, true);

                TUtils.CProcessException.Process(
                    ref mdsFinal // mdsFinal
                    , _log // log
                    , _strConfig_GwUserCode // strGwUserCodeForLog
                    , _strConfig_GwUserPasswordForLog // strGwPasswordForLog
                    , strFunctionName // strFunctionName
                    , TUtils.CUtils.TidNext(strTid, ref nTidSeq) // strAppTid
                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") // strAppTDateTime
                    , strPartnerCode // strAppServiceCode
                    , strPartnerUserCode // strAppUserCode
                    , strLanguageCode // strLanguageCode
                    , "" // strRemark
                    );
                #endregion
            }
        }
        #endregion

		void ProcessUpdateCustomerDebit(string strCusID, string strDebit, string strReceiptType)
		{
			#region // Save data
			string strSqlDelete = string.Empty;
			if (strReceiptType.Equals("TRA_NO"))
			{
				strSqlDelete = @"
						Update Water_Customer 
						Set Debit=Debit -@Debit
						where (1=1)
							and CusID = @CusID
							--and ReceiptType='TRA_NO'
						;
					";
			}

			if (strReceiptType.Equals("TRA_VO"))
			{
				strSqlDelete = @"
						Update Water_Customer 
						Set NoVoCurrent=NoVoCurrent -@Debit
						where (1=1)
							and CusID = @CusID
							--and ReceiptType='TRA_VO'
						;
					";
			}
			if (strReceiptType.Equals("TRA_CUOCVO"))
			{
				strSqlDelete = @"
						Update Water_Customer 
						Set CuocVoCurrent=CuocVoCurrent -@Debit
						where (1=1)
							and CusID = @CusID
							--and ReceiptType='TRA_VO'
						;
					";
			}

			// Save:
			
			_dbCarSv.ExecQuery(
				strSqlDelete
				, "@CusID", strCusID
				, "@Debit", strDebit
				);
			#endregion
		}

        #endregion
        
    }
}
